package com.ruoyi.finance.withdrawOrder.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.finance.livestreaming.entity.SzEnergyRecord;
import com.ruoyi.finance.livestreaming.entity.SzWithdrawalDetail;
import com.ruoyi.finance.livestreaming.mapper.SzEnergyRecordMapper;
import com.ruoyi.finance.livestreaming.mapper.SzWithdrawalDetailMapper;
import com.ruoyi.finance.livestreaming.mapper.SzWithdrawalRecordMapper;
import com.ruoyi.finance.rules.entity.SzOtherRule;
import com.ruoyi.finance.rules.entity.SzUser;
import com.ruoyi.finance.rules.mapper.SzUserMapper;
import com.ruoyi.finance.rules.task.SZRuleCache;
import com.ruoyi.module.utils.BigDecimalChain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.finance.withdrawOrder.mapper.RYWithdrawalRecordMapper;
import com.ruoyi.finance.withdrawOrder.domain.SzWithdrawalRecord;
import com.ruoyi.finance.withdrawOrder.service.RYWithdrawalRecordService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 提现订单Service业务层处理
 *
 * @author wangmh
 * @date 2023-10-24
 */
@Slf4j
@Service
public class RYWithdrawalRecordServiceImpl implements RYWithdrawalRecordService {
    @Autowired
    private RYWithdrawalRecordMapper RYWithdrawalRecordMapper;
    @Autowired
    private SzWithdrawalRecordMapper szWithdrawalRecordMapper;
    @Autowired
    private SzUserMapper szUserMapper;
    @Autowired
    private SZRuleCache ruleCache;
    @Autowired
    private SzEnergyRecordMapper szEnergyRecordMapper;
    @Autowired
    private SzWithdrawalDetailMapper szWithdrawalDetailMapper;

    /**
     * 查询提现订单
     *
     * @param id 提现订单主键
     * @return 提现订单
     */
    @Override
    public SzWithdrawalRecord selectSzWithdrawalRecordById(Long id) {
        return RYWithdrawalRecordMapper.selectSzWithdrawalRecordById(id);
    }

    /**
     * 查询提现订单列表
     *
     * @param szWithdrawalRecord 提现订单
     * @return 提现订单
     */
    @Override
    public List<SzWithdrawalRecord> selectSzWithdrawalRecordList(SzWithdrawalRecord szWithdrawalRecord) {
        return RYWithdrawalRecordMapper.selectSzWithdrawalRecordList(szWithdrawalRecord);
    }

    /**
     * 新增提现订单
     *
     * @param szWithdrawalRecord 提现订单
     * @return 结果
     */
    @Override
    public int insertSzWithdrawalRecord(SzWithdrawalRecord szWithdrawalRecord) {
        return RYWithdrawalRecordMapper.insertSzWithdrawalRecord(szWithdrawalRecord);
    }

    /**
     * 修改提现订单
     *
     * @param szWithdrawalRecord 提现订单
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult updateSzWithdrawalRecord(SzWithdrawalRecord szWithdrawalRecord) {
        if (szWithdrawalRecord.getId() == null || StringUtil.isEmpty(szWithdrawalRecord.getState())){
            return AjaxResult.error("参数为空");
        }

        com.ruoyi.finance.livestreaming.entity.SzWithdrawalRecord withdrawalRecord = szWithdrawalRecordMapper.selectById(szWithdrawalRecord.getId());

        // 发放操作
        if ("2".equals(szWithdrawalRecord.getState())){
            if("3".equals(withdrawalRecord.getState())){
                return AjaxResult.error("用户已取消，无法发放");
            }

            if ("4".equals(withdrawalRecord.getState())){
                return AjaxResult.error("已驳回的订单无法发放");
            }

            if ("2".equals(withdrawalRecord.getState())){
                return AjaxResult.error("此订单已发放，请勿重复操作");
            }

            withdrawalRecord.setRemark("正常发放");
            withdrawalRecord.setState("2");

            // 扣除提现余额
            this.insertWithdrawalRecord(withdrawalRecord);
        }

        // 驳回
        if ("4".equals(szWithdrawalRecord.getState())){
            if("3".equals(withdrawalRecord.getState())){
                return AjaxResult.error("用户已取消，无法驳回");
            }

            if ("2".equals(withdrawalRecord.getState())){
                return AjaxResult.error("已发放的订单无法发放");
            }

            if ("4".equals(withdrawalRecord.getState())){
                return AjaxResult.error("此订单已驳回，请勿重复操作");
            }

            withdrawalRecord.setRemark(szWithdrawalRecord.getRemark());
            withdrawalRecord.setState("4");

            // 恢复暂扣金额
            this.recoverWithdrawalRecord(withdrawalRecord);
        }

        withdrawalRecord.setHandleTime(LocalDateTime.now());
        withdrawalRecord.setHandlePerson(SecurityUtils.getUserId());
        szWithdrawalRecordMapper.updateById(withdrawalRecord);
        return AjaxResult.success("操作成功");
    }

    private void insertWithdrawalRecord(com.ruoyi.finance.livestreaming.entity.SzWithdrawalRecord withdrawalRecord){
        Long userId = withdrawalRecord.getUserId();
        SzUser user = szUserMapper.selectById(userId);
        BigDecimal actualArrival = withdrawalRecord.getActualArrival();
        BigDecimal amount = withdrawalRecord.getMoney();
        log.info("用户{}发起提现操作发放成功，本次提现金额为{}，税收比例{}，提现手续费{}，提现账号{}，实际到账{}，处理结果{}",
                user.getNickname(), amount,withdrawalRecord.getRevenueRatio(),withdrawalRecord.getExtractRatio(), withdrawalRecord.getAccount(), actualArrival, withdrawalRecord.getRemark());

//        user.setSzWithdrawalBalance(BigDecimalChain.chain(user.getSzWithdrawalBalance()).sub(amount).get());
//        user.setSzEnergy(BigDecimalChain.chain(user.getSzEnergy()).sub(amount).get());
//        szUserMapper.updateById(user);
//        log.info("扣除用户提现余额、能量值成功");

        SzEnergyRecord energyRecord = new SzEnergyRecord();
        energyRecord.setUserId(userId);
        energyRecord.setCreateTime(LocalDateTime.now());
        energyRecord.setEnergy(amount);
        energyRecord.setType("2");
        szEnergyRecordMapper.insert(energyRecord);
        log.info("保存能量值变化明细成功");

//        SzWithdrawalDetail withdrawalDetail = new SzWithdrawalDetail();
//        withdrawalDetail.setUserId(userId);
//        withdrawalDetail.setMoney(amount);
//        withdrawalDetail.setFlowType("1"); // 提现
//        withdrawalDetail.setTakeoutId(withdrawalRecord.getId());
//        withdrawalDetail.setCreateTime(LocalDateTime.now());
        SzWithdrawalDetail withdrawalDetail = szWithdrawalDetailMapper.selectOne(new LambdaQueryWrapper<SzWithdrawalDetail>().eq(SzWithdrawalDetail::getTakeoutId, withdrawalRecord.getId()));
        withdrawalDetail.setFlowType("1");
        szWithdrawalDetailMapper.updateById(withdrawalDetail);
        log.info("保存提现钱包明细记录成功");
    }

    private void recoverWithdrawalRecord(com.ruoyi.finance.livestreaming.entity.SzWithdrawalRecord withdrawalRecord){
        Long userId = withdrawalRecord.getUserId();
        SzUser user = szUserMapper.selectById(userId);
        BigDecimal actualArrival = withdrawalRecord.getActualArrival();
        BigDecimal amount = withdrawalRecord.getMoney();
        log.info("用户{}发起提现操作发放失败，操作被驳回，本次提现金额为{}，税收比例{}，提现手续费{}，提现账号{}，实际到账{}，处理结果{}",
                user.getNickname(), amount,withdrawalRecord.getRevenueRatio(),withdrawalRecord.getExtractRatio(), withdrawalRecord.getAccount(), actualArrival, withdrawalRecord.getRemark());

        user.setSzWithdrawalBalance(BigDecimalChain.chain(user.getSzWithdrawalBalance()).add(amount).get());
        user.setSzEnergy(BigDecimalChain.chain(user.getSzEnergy()).add(amount).get());
        szUserMapper.updateById(user);
        log.info("扣除用户提现余额");

        SzWithdrawalDetail withdrawalDetail = szWithdrawalDetailMapper.selectOne(new LambdaQueryWrapper<SzWithdrawalDetail>().eq(SzWithdrawalDetail::getTakeoutId, withdrawalRecord.getId()));
        withdrawalDetail.setFlowType("12");
        szWithdrawalDetailMapper.updateById(withdrawalDetail);
        log.info("保存提现钱包明细记录成功");
    }


    /**
     * 批量删除提现订单
     *
     * @param ids 需要删除的提现订单主键
     * @return 结果
     */
    @Override
    public int deleteSzWithdrawalRecordByIds(Long[] ids) {
        return RYWithdrawalRecordMapper.deleteSzWithdrawalRecordByIds(ids);
    }

    /**
     * 删除提现订单信息
     *
     * @param id 提现订单主键
     * @return 结果
     */
    @Override
    public int deleteSzWithdrawalRecordById(Long id) {
        return RYWithdrawalRecordMapper.deleteSzWithdrawalRecordById(id);
    }
}
